import java.io.*;
import java.lang.reflect.Method;

public class HelloClassLoader extends ClassLoader {

    private String path = "/home/luciel/";    //默认加载路径

    private final String filetype = ".xlass"; //文件类型

    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        byte[] b = loadClassData(name);
        for (int i = 0; i < b.length; i++) {
            b[i] = (byte) (255 - b[i]);
        }

        return defineClass(name, b, 0, b.length);
    }

    private byte[] loadClassData(String name) {
        byte[] data = null;
        InputStream in = null;
        name = name.replace('.', '/');
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try {
            in = new FileInputStream(new File(path + name + filetype));
            int len = 0;
            while (-1 != (len = in.read())) {
                out.write(len);
            }
            data = out.toByteArray();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                in.close();
                out.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return data;
    }


    public static void main(String[] args) throws Exception {

        String resourcePath = HelloClassLoader.class.getResource("/").getFile();
        System.out.println(resourcePath);

        HelloClassLoader loader = new HelloClassLoader();
        loader.path = resourcePath + "/";
        Class<?> c = loader.loadClass("Hello");
        Method[] declaredMethods = c.getDeclaredMethods();
        for (Method declaredMethod : declaredMethods) {
            System.out.println(declaredMethod);
        }
    }
}
